package cn.itsub.sodo.view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Panel;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import cn.itsub.sodo.core.types.Size;

public class GraphicsView extends HiView{ 

	public static GraphicsView create(Size frameSize,Size designSize){
		GraphicsView view = new GraphicsView(frameSize,designSize);
		return view;
	}
	
    //构造方法 
    public GraphicsView(Size frameSize,Size designSize){ 
    	this.frameSize = frameSize;
    	this.designSize = designSize;
    	this.frame = new Frame("HiGame");
        DrawCanvas canvas = new DrawCanvas(this);//实例化画布 
        //frame.add(canvas); 
        frame.setBackground(new Color(0,0,0));//设置背景颜色 
        frame.setLocationByPlatform(true); 
        frame.setSize((int)frameSize.width,(int)frameSize.height); 
        frame.setResizable(false);
        frame.setVisible(true);
        
        frame.setLayout(new BorderLayout());
        frame.add(canvas, BorderLayout.CENTER);
        
        Insets set=frame.getInsets();
        frame.setSize((int)frameSize.width+set.left+set.right, (int)frameSize.height+set.top+set.bottom);
        
        frame.addWindowListener(new WindowAdapter() {
        	public void windowClosing(WindowEvent e) {
        		System.exit(0);
        	}
		});
        canvas.addFocusListener(new FocusAdapter() {
        	public void focusGained(FocusEvent e) {
        		System.out.println("Gained-----");
        		frame.requestFocusInWindow();
        	}
		});
        
    } 
    
	@Override
	public HiView init(Size frameSize, Size designSize) {
		return this;
	} 
   
}

class DrawCanvas extends Panel{ //新建画布类 
	private HiView view = null;
	public DrawCanvas(HiView view) {
		this.view = view;
		this.view.canvas = this;
	}
	
	
	
    @Override//重写方法 
    public void paint(Graphics g){
		Graphics2D g2 = (Graphics2D) g;
		
		float scaleX = this.getWidth()/view.designSize.width;
		float scaleY = this.getHeight()/view.designSize.height;
		g2.scale(scaleX, scaleY);
		
        //Director.getInstance().drawScene(g2);
        
        g2.drawLine(0, 0, 600, 400);

    } 
    int n = 0;
    /* ----- 双缓冲技术，解决重绘闪烁 ----- */
    Image ImageBuffer = null;  
    Graphics GraImage = null;   
    public void update(Graphics g){     //覆盖update方法，截取默认的调用过程  
        ImageBuffer = createImage(this.getWidth(), this.getHeight());   //创建图形缓冲区  
        GraImage = ImageBuffer.getGraphics();       //获取图形缓冲区的图形上下文  
        paint(GraImage);        //用paint方法中编写的绘图过程对图形缓冲区绘图  
        GraImage.dispose();     //释放图形上下文资源  
        g.drawImage(ImageBuffer, 0, 0, this);   //将图形缓冲区绘制到屏幕上  
        System.out.println(n++);
    }  

}